<template>
  <el-form label-width="100px" label-position="left" class="create-work-wrapper">
    
      <el-form-item label="作业标题">
          <el-input v-model="form.title" size="small"></el-input>
      </el-form-item>
      <el-form-item label="选择课程">
          <el-select v-model="form.course" size="small">
              <el-option v-for="(item, index) in courses" :key="index" :value="item.id" :label="item.course_name"></el-option>
          </el-select>
      </el-form-item>
      <el-form-item label="提交截止时间">
          <el-date-picker
            v-model="form.deadline"
            size="small"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期">
            </el-date-picker>
      </el-form-item>
      <el-form-item label="编辑题目">
          <div v-for="(question, index) in form.questions" :key="index" class="question-item">
              <p>题目{{index+1}}</p>
              <el-input v-model="question.text" type="textarea" size="medium"  :autosize="{ minRows: 1, maxRows: 12}" clearable>
              </el-input>
              <p>参考答案</p>
              <el-input v-model="question.answer" type="textarea" size="medium"  :autosize="{ minRows: 4, maxRows: 12}"  clearable></el-input>
              <i class="el-icon-close close-icon" @click="removeQuestion(index)"></i>
          </div>
          <el-button size="small" class="add-btn" @click="appendQuestion">
              <img src="../assets/添加灰.png" alt="添加">
          </el-button>
      </el-form-item>
      <!-- <el-form-item label="答案发布时间">
        <el-radio-group v-model="form.pubdate">
          <el-radio label="一天后"></el-radio>
          <el-radio label="两天后"></el-radio>
          <el-radio label="立刻"></el-radio>
        </el-radio-group>
      </el-form-item> -->
      <el-form-item>
        <el-button  type="primary" size="small" class="confirm-btn" @click="createTask">确定</el-button>
      </el-form-item>
  </el-form>
</template>
<script>
import { getMyCourse, createTask, getTask, updateWork} from '@/utils/api'

export default {
  name: 'CreateWork',
  data() {
    return {
      form: {
        title: '',
        course: '',
        deadline: '',
        questions: [{
          content: '',
          answer: ''
        }],
        pubdate: ''
      }
    }
  },
  computed: {
    courses () {
      return this.$store.state.courses
    }
  },
  mounted () {
    if (!this.courses.length) {
      this.getMyCourse()
    }
    console.log(this.$route)
    if(this.$route.params.title){
      Object.assign(this.form, this.$route.params)
      console.log(this.form)
    }
  },
  methods: {
    removeQuestion (index) {
      this.form.questions.splice(index, 1)
    },
    appendQuestion () {
      this.form.questions.push({text: '', answer: ''})
    },
    async getMyCourse () {
      let res = await getMyCourse()
      if (res.error === '10') {
        this.$store.commit('setCourses', res.result)
      } else {
        this.$notify({
          title: '获取课程出错',
          message: res.result,
          type: 'error'
        })
      }
    },
    checkField () {
      let form = {
        title: this.form.title.trim(),
        course_id: this.form.course,
        assignment_id: this.form.assignment_id,
        dead_line: this.form.deadline,
        type: '0',
        tis: this.getQuestionsContent()
      }
      for (let key in form) {
        if (key==='assignment_id')
        {
          continue
        }
        if ((typeof form[key] === 'string' && form[key].length <= 0) || !form[key]) {
          this.$notify({
            title: '请完整填写',
            message: '请完整填写',
            type: 'warning'
          })
          
          return false
        } else if (typeof form[key] === 'object') {
          if (!form[key].length) {
            this.$notify({
              title: '请完整填写',
              message: '至少要填写一个题目',
              type: 'warning'
            })
          }
          for (let index in form[key]) {
            if ((typeof form[key][index] === 'string' && form[key][index].length <= 0) || !form[key].length) {
              this.$notify({
                title: '请完整填写',
                message: '请完整填写',
                type: 'warning'
              })
              return false
            }
          }
        }
      }
      return form
    },
    getQuestionsContent () {
      let res = []
      this.form.questions.map((item) => { 
        res.push({
          question: item.text,
          answer: item.answer,
          id: item.ti_id
        })         
      })
      return res
    },
    timestampToTime (timestamp) {
      console.log(timestamp)
      let date = new Date(timestamp)
      console.log(date.getFullYear())
      let Y = date.getFullYear() + '-'
      let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
      let D = date.getDate()
      return Y + M + D
    },
    async createTask () {
      let form = this.checkField()
      if (form) {
        let res = await (this.$route.params.title?  updateWork(form) : createTask(form))
        console.log(res)
        if (res.error === '10') {
          let target = await getTask({ filter_by_course_id: '', assignment_type: '0' })
          if (target.error === '10') {
            this.$store.commit('setTasks', target.result)
            this.$notify({
              title: '操作成功',
              type: 'success'
            })
          }
          this.$router.push('./work')
        } else {
          this.$notify({
            title: '操作失败',
            message: `原因: ${res.result}`,
            type: 'error'
          })
        }
      }
    }
  }
}
</script>

<style lang="less">
.create-work-wrapper {
    padding-top: 45px;
    width: 60%;
    margin: 0 auto;
    @media screen  and (max-width: 768px){
      width: 90%;
      margin: 0;
      padding: 20px;
    }
    input {
        border-radius: 0;
        max-width: 400px;
    }
    textarea {
        border-radius: 0;
        padding: 10px 40px;
        text-align: left;
    }
    .question-item {
        margin-bottom: 20px;
        position: relative;
        border: 1px solid #c9cdd3;
        border-radius: 4px;
        padding: 0 20px 20px;
        @media screen  and (max-width: 768px){
          top: 40px;
          left: -100px;
          width: 300px;
        }
        p {
          margin: 5px 0;
          height: 30px;
        }
        .close-icon {
          position: absolute;
          top: 10px;
          right: 10px;
          font-size: 20px;
        }
    }
    .add-btn {
        width: 100%;
        height: 30px;
        padding: 0;
        border-radius: 0;
        border: 0;
        background: #fff;
        img {
            height: 100%;
        }
         @media screen  and (max-width: 768px){
          margin-top: 40px;
          margin-left: -100px;
          width: 342px;
        }
    }
    .confirm-btn {
      border-radius: 4;
      float: right;
      width: 100px;
      position: relative;
      margin-left: 75%;
      @media screen {
        float: none;
        margin-right: 0;
      }
    }
}
</style>
